import json

from openai import OpenAI
from datetime import datetime

"""
reflection的核心在于：对自己的产出结果进行检查，并结合实际输出情况进行优化和改进。
"""

api_key = '3dddcf7b2b836113433294985212a4f0.bvmegyRgPZcO7Pvj'
base_url = 'https://open.bigmodel.cn/api/paas/v4/'
model = 'glm-4-flash-250414'
client = OpenAI(api_key=api_key, base_url=base_url)


def get_current_time():
    """
    Returns the current time as a string.
    """
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")


# Write a text file
def write_txt_file(file_path: str, content: str):
    """
    Write a string into a .txt file (overwrites if exists).
    Args:
        file_path (str): Destination path.
        content (str): Text to write.
    Returns:
        str: Path to the written file.
    """
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(content)
    return file_path


# 定义函数描述
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "获取当前的时间，返回格式：%Y-%m-%d %H:%M:%S",
            "parameters": {
                "type": "object",
                "properties": {},
                "required": []
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "write_txt_file",
            "description": "把一段文本写到指定的文件中",
            "parameters": {
                "type": "object",
                "properties": {
                    "file_path": {
                        "type": "string",
                        "description": "文件路径，例如：a.txt"
                    },
                    "content": {
                        "type": "string",
                        "description": "文本内容"
                    },
                },
                "required": ["file_path", "content"]
            }
        }
    }
]


def chat():
    messages = []
    while True:
        question = input("你有什么需要帮忙呢？")
        if question == "exit":
            break
        elif not question:
            continue
        messages.append({"role": "user", "content": question})

        # 调用带函数的对话
        response = client.chat.completions.create(
            model=model,
            messages=messages,
            tools=tools,
            tool_choice="auto"
        )

        message = response.choices[0].message

        # 用循环持续处理多层函数调用
        while message.tool_calls:
            for tool_call in message.tool_calls:
                func_name = tool_call.function.name
                args = json.loads(tool_call.function.arguments or "{}")

                if func_name == "get_current_time":
                    result = get_current_time()
                elif func_name == "write_txt_file":
                    result = write_txt_file(**args)
                else:
                    result = "❌ 未知函数"

                print(f"函数调用结果: {result}")
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": str(result)
                })

            # 关键：继续调用模型，让它决定下一步
            response = client.chat.completions.create(
                model=model,
                messages=messages,
                tools=tools,
                tool_choice="auto"
            )
            message = response.choices[0].message

        # 如果没有更多函数调用，输出最终回答
        answer = message.content.strip()
        print(f"AI回复: {answer}")
        messages.append({"role": "assistant", "content": answer})


if __name__ == '__main__':
    chat()
